
// 1.1 生成指定范围随机数
function getRandomNumber1(min:number, max:number) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
}

// 示例
console.log(getRandomNumber(5, 10)); // 输出5-10之间的随机整数
// 2.1 数组乱序

function shuffleArray1(array:any) {
    return array.sort(() => Math.random() - 0.5);
}
// 2.2 数组扁平化
function flattenArray1<T>(arr: (T | T[])[]): T[] {
    return arr.reduce<T[]>((acc, val) => 
      Array.isArray(val) ? acc.concat(flattenArray(val)) : acc.concat(val), 
    []);
  }
// 2.3 数组中获取随机数
function getRandomElement1(array:number[]):number {
    return array[Math.floor(Math.random() * array.length)];
  }
  console.log(getRandomElement([1, 2, 3, 4, 5])); // 随机返回数组中的一个元素
// 3.1 生成随机字符串
function generateRandomString1(length:number = 8):string {
    const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
    let result:string = '';
    for (let i = 0; i < length; i++) {
      result += chars.charAt(Math.floor(Math.random() * chars.length));
    }
    return result;
  }
  console.log(generateRandomString(10));
  // 3.2 字符串首字母大写
function capitalizeFirstLetter1(str:string) {
    return str.charAt(0).toUpperCase() + str.slice(1);
  }
  // 3.3 手机号中间四位变成*
function maskPhoneNumber1(phone:string) {
    return phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2');
  }
  // 3.4 驼峰命名转换成短横线命名  userName UserName user_name
function camelToKebab1(str:string) {
    return str.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase();
  }
  
  // 示例
  console.log(camelToKebab('userName')); // "user-name"
  console.log(camelToKebab('UserName')); // "user-name"
// 3.5 短横线命名转换成驼峰命名
function kebabToCamel1(str:string) {
    return str.replace(/-([a-z])/g, (_, letter) => letter.toUpperCase());
  }
  
  // 示例
  console.log(kebabToCamel('user-name')); // "userName"
  // 4.1 数字转化为大写金额
function numberToChinese1(num:number) {
    if (isNaN(num)) return '非法数字';
    const digits = ['零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖'];
    const units = ['', '拾', '佰', '仟', '万', '拾', '佰', '仟', '亿', '拾', '佰', '仟', '兆'];
    const decimals = ['角', '分', '厘'];
    
    let str = '';
    num = Math.abs(num);
    
    // 整数部分
    const integer = Math.floor(num);
    if (integer > 0) {
      let integerStr = '';
      const integerArr = integer.toString().split('').reverse();
      integerArr.forEach((item, index) => {
        const digit = digits[parseInt(item)];
        const unit = units[index];
        integerStr = digit + unit + integerStr;
      });
      str += integerStr + '元';
    }
    
    // 小数部分
    const decimal = Math.round((num - integer) * 100) / 100;
    if (decimal > 0) {
      const decimalStr = decimal.toString().substring(2);
      for (let i = 0; i < decimalStr.length; i++) {
        if (i >= decimals.length) break;
        str += digits[parseInt(decimalStr[i])] + decimals[i];
      }
    } else {
      str += '整';
    }
    
    return str;
  }
  
  // 示例
  console.log(numberToChinese(12345.67)); // "壹万贰仟叁佰肆拾伍元陆角柒分"
  // 5.1 存储 localStorage
function setLocalStorage1(key:string, value:any) {
    localStorage.setItem(key, JSON.stringify(value));
  }
  
  // 5.2 获取 localStorage
  function getLocalStorage1(key:string) {
    const value = localStorage.getItem(key);
    return value ? JSON.parse(value) : null;
  }
  
  // 5.3 删除 localStorage
  function removeLocalStorage1(key:string) {
    localStorage.removeItem(key);
  }
  // 6.1 设置 cookie
function setCookie1(name:string, value:string, days:number = 7) {
    const date = new Date();
    date.setTime(date.getTime() + days * 24 * 60 * 60 * 1000);
    document.cookie = `${name}=${encodeURIComponent(value)};expires=${date.toUTCString()};path=/`;
  }
  
  // 6.2 读取 cookie
  function getCookie1(name:string) {
    const cookies = document.cookie.split(';');
    for (let cookie of cookies) {
      const [key, value] = cookie.trim().split('=');
      if (key === name) return decodeURIComponent(value);
    }
    return null;
  }


// 7.1 正则校验身份证号码
function validateIDCard1(id: string): boolean {
    const reg = /^[1-9]\d{5}(18|19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}[\dXx]$/;
    return reg.test(id);
}

// 7.2 正则校验是否包含中文
function hasChinese1(str: string): boolean {
    return /[\u4e00-\u9fa5]/.test(str);
}

  // 8.1 获取URL参数列表
// 8.1 获取URL参数列表
function getUrlParams1(): Record<string, string> {
    const params: Record<string, string> = {};
    new URLSearchParams(window.location.search).forEach((value, key) => {
        params[key] = value;
    });
    return params;
}

function buildUrlParams1(params: Record<string, string | number | boolean>): string {
    const searchParams = new URLSearchParams();
    
    for (const key in params) {
      if (params.hasOwnProperty(key)) {
        const value = params[key];
        if (value !== undefined && value !== null) {
          searchParams.append(key, String(value));
        }
      }
    }
    
    return searchParams.toString();
  }
  
  // 使用示例
  const params1 = {
    name: "John Doe",
    age: 30,
    active: true,
    query: "typescript url params"
  };
  
  const queryString1 = buildUrlParams(params);
  console.log(queryString);
  // 输出: "name=John+Doe&age=30&active=true&query=typescript+url+params"

// 9.1 判断是移动还是PC设备
function isMobile1(): boolean {
    return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
}
  
  // 9.4 判断是Windows还是Mac系统
  function getOS1() {
    const userAgent = navigator.userAgent;
    if (/Mac/i.test(userAgent)) return 'Mac';
    if (/Win/i.test(userAgent)) return 'Windows';
    return 'Unknown';
  }

// 10.1 滚动到页面顶部
function scrollToTop1() {
    window.scrollTo({
      top: 0,
      behavior: 'smooth' // 平滑滚动
    });
    
    // 或者使用兼容性更好的写法
    // const top = document.documentElement.scrollTop || document.body.scrollTop;
    // if (top > 0) {
    //   window.requestAnimationFrame(scrollToTop);
    //   window.scrollTo(0, top - top / 8);
    // }
  }
  
  // 10.4 获取可视窗口高度
  function getViewportHeight1() {
    return window.innerHeight || 
           document.documentElement.clientHeight || 
           document.body.clientHeight;
  }

// 11.2 格式化时间
function formatTime1(date: Date | string | number, fmt = 'YYYY-MM-DD HH:mm:ss'): string {
    if (!(date instanceof Date)) {
        date = new Date(date);
    }
    
    const padZero = (num: number): string => (num < 10 ? `0${num}` : num.toString());
    
    const map: Record<string, string> = {
        'YYYY': date.getFullYear().toString(),
        'MM': padZero(date.getMonth() + 1),
        'DD': padZero(date.getDate()),
        'HH': padZero(date.getHours()),
        'mm': padZero(date.getMinutes()),
        'ss': padZero(date.getSeconds())
    };
    
    return fmt.replace(/(YYYY|MM|DD|HH|mm|ss)/g, (match) => map[match]);
}

// 12.2 防抖函数
function debounce1<T extends (...args: any[]) => any>(fn: T, delay = 300): (...args: Parameters<T>) => void {
    let timer: ReturnType<typeof setTimeout> | null = null;
    return function(this: ThisParameterType<T>, ...args: Parameters<T>): void {
        if (timer) clearTimeout(timer);
        timer = setTimeout(() => {
            fn.apply(this, args);
            timer = null;
        }, delay);
    };
}

// 12.3 节流函数
function throttle1<T extends (...args: any[]) => any>(fn: T, interval = 300): (...args: Parameters<T>) => void {
    let lastTime = 0;
    return function(this: ThisParameterType<T>, ...args: Parameters<T>): void {
        const now = Date.now();
        if (now - lastTime >= interval) {
            fn.apply(this, args);
            lastTime = now;
        }
    };
}

// 12.5 对象深拷贝
function deepClone1<T>(obj: T, hash = new WeakMap()): T {
    // 处理基本类型和 null/undefined
    if (obj === null || typeof obj !== 'object') {
      return obj;
    }
  
    // 处理日期对象
    if (obj instanceof Date) {
      return new Date(obj.getTime()) as unknown as T;
    }
  
    // 处理正则表达式
    if (obj instanceof RegExp) {
      return new RegExp(obj.source, obj.flags) as unknown as T;
    }
  
    // 处理数组
    if (Array.isArray(obj)) {
      return obj.map(item => deepClone(item, hash)) as unknown as T;
    }
  
    // 处理 Map
    if (obj instanceof Map) {
      const clonedMap = new Map();
      obj.forEach((value, key) => {
        clonedMap.set(deepClone(key, hash), deepClone(value, hash));
      });
      return clonedMap as unknown as T;
    }
  
    // 处理 Set
    if (obj instanceof Set) {
      const clonedSet = new Set();
      obj.forEach(value => {
        clonedSet.add(deepClone(value, hash));
      });
      return clonedSet as unknown as T;
    }
  
    // 检查循环引用
    if (hash.has(obj)) {
      return hash.get(obj);
    }
  
    // 处理普通对象
    const clonedObj = Object.create(Object.getPrototypeOf(obj));
    hash.set(obj, clonedObj);
  
    for (const key in obj) {
      if (obj.hasOwnProperty(key)) {
        clonedObj[key] = deepClone(obj[key], hash);
      }
    }
  
    return clonedObj;
  }
  
//   // 使用示例
//   const complexObj = {
//     date: new Date(),
//     regex: /test/g,
//     map: new Map([['key', 'value']]),
//     set: new Set([1, 2, 3]),
//     selfRef: {} as any
//   };
//   complexObj.selfRef = complexObj;
  
//   const clonedComplex = deepClone(complexObj);
//   console.log(clonedComplex);

